from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager

class CustomedUserManager(BaseUserManager):
    def create_user(self, email, username, password=None, **kwargs):
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            email=self.normalize_email(email),
            username=username,
            **kwargs
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, username, password, **kwargs):
        kwargs.setdefault('is_staff', True)
        kwargs.setdefault('is_superuser', True)
        
        return self.create_user(email, username, password, **kwargs)
class CustomedUser(AbstractBaseUser):
    email = models.EmailField(unique=True)
    password = models.CharField(max_length=128)
    username = models.CharField(max_length=30, unique=True)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    AIPic = models.CharField(max_length=128,default="static/img/chatgpt.jpg")
    credit = models.FloatField(default=0.0)
    modelName =models.CharField(max_length = 128 ,default = "ChatGPT")
    objects = CustomedUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    def __str__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, app_label):
        return True



from django.contrib.auth.backends import ModelBackend

class EmailOrNicknameModelBackend(ModelBackend):
    """
    自定义身份验证后端，可以使用邮箱或者昵称进行登录验证
    """

    def authenticate(self, request, username=None, password=None, **kwargs):
        """
        重写身份验证方法，允许使用邮箱或者昵称进行登录验证
        """


        # 判断用户名是否为空
        if username is None:
            username = kwargs.get(CustomedUser.USERNAME_FIELD)

        try:
            # 判断用户名是否为邮箱
            if '@' in username:
                user = CustomedUser.objects.get(email__iexact=username)

            # 否则，认为用户名为昵称
            else:
                user = CustomedUser.objects.get(username__iexact=username)

        except CustomedUser.DoesNotExist:
            # 如果用户不存在，返回None
            return None

        # 如果密码验证通过，返回用户对象
        if user.check_password(password):
            return user

        # 如果密码验证不通过，返回None
        return None